package com.istock.state.demo.service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.istock.state.demo.constants.OrderInfoStatusEnum;
import com.istock.state.demo.dao.OrderInfoMapper;
import com.istock.state.demo.model.OrderInfo;
import com.istock.state.demo.model.OrderInfoExample;

@Repository("orderInfoService")
public class OrderInfoService {

	@Autowired
	private OrderInfoMapper orderInfoMapper;
	
	public OrderInfo createOrderInfo(String name , Integer status , BigDecimal amount) {
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setAmount(amount);
		orderInfo.setStatus(status);
		orderInfo.setName(name);
		orderInfo.setUpdateTime(new Date());
		orderInfoMapper.insertSelective(orderInfo);
		
		return orderInfo;
	}
	
	/**定时任务查询
	 * 查询超期的符合补单状态的orderInfo
	 * 超期的含义是在过去5分钟-2小时的订单
	 * @return
	 */
	public List<OrderInfo> findExpireOrderInfo(){
		OrderInfoExample example = new OrderInfoExample();
		OrderInfoExample.Criteria criteria = example.createCriteria();
		
		criteria.andUpdateTimeBetween(DateUtils.addMinutes(new Date(), -30),DateUtils.addSeconds(new Date(), -1));
		criteria.andStatusIn(Arrays.asList(OrderInfoStatusEnum.NO_PAY.getValue() 
				, OrderInfoStatusEnum.PAYED.getValue()));
		//这边为了防止单次查询的数据量过多,可以增加orderBy和分页
		return orderInfoMapper.selectByExample(example);
		
	}
	
	public OrderInfo findOrderInfoById(Long id) {
		return orderInfoMapper.selectByPrimaryKey(id);
	}
}
